var db_id = 'bookmark_setting_id';


var ins = axios.create();
ins.defaults.async=false;

layui.use(function(){
    var element = layui.element;
    var table = layui.table;
    var tree = layui.tree;
    var form = layui.form;
    var layer = layui.layer;
    var laytpl = layui.laytpl;
    var util = layui.util;
    var $ = layui.$;


    //初始化数据
    var dbObj = utools.db.get(db_id);
    form.val('setting_form',dbObj);

    renderLocalCheck()
    renderSettingLocalDir();

    
    
    // 导航点击事件
    element.on('nav(nav)', function(elem){
        $('.nav_panel').addClass('display_none');
        $("#"+elem.attr('k')+"").removeClass('display_none');
    });

    form.on('submit(setting_save)', function(data){
        var tableData = table.getData('local_table');
        data.field.local_folder = tableData[0].dir
        data.field.local_folder_name = tableData[0].alias
        data.field.local_folder1 = tableData[1].dir
        data.field.local_folder1_name = tableData[1].alias
        data.field.local_folder2 = tableData[2].dir
        data.field.local_folder2_name = tableData[2].alias
        saveToDb(data.field)
        renderLocalCheck();
        layer.msg('保存成功',{offset:'16px',icon: 1})
    });

    $('#refresh').on('click',function(){
        dbObj = utools.db.get(db_id);
        form.val('setting_form',dbObj)
        renderSettingLocalDir();
        layer.msg('加载完成',{offset:'16px',icon: 1})
    })

    $('#localReload').on('click',function(){
        loadLocal();
    })

    $('#localPush').on('click',function(){
        layer.confirm('推送会覆盖仓库书签，确定吗？', {icon: 3}, function(index){
            layer.close(index)
            localPush();
        });
    })

    $('#remoteReload').on('click',function(){
        loadRemote();
    })

    $('#remoteDownload').on('click',function(){
        dbObj = utools.db.get(db_id);


        var localCheckObj = getLocalCheckOrDef();
        var localDir = localCheckObj.dir;
        var localAlias = localCheckObj.alias;


        layer.confirm('下载会【强制覆盖】本地书签，确定吗？<br>【'+localAlias+'】'+localDir, {icon: 3}, function(index){
            layer.close(index);
            
            window.services.backup(localDir)
            .then(function(){
                return queryRemote(dbObj)
            })
            .catch(err => {
                if(err.errno == -4058){
                    layer.msg('【本地书签地址】没找到：<br>'+err.path,{offset:'16px',icon: 5})
                }
            })
            .then(data => {
                var str = Base64.decode(data.data.content);
                window.services.writeFile(localDir,str);
                layer.msg('保存成功,重启浏览器生效',{offset:'16px',icon: 1})
            }).catch(giteeFailed);
        });
    })

    function renderLocalCheck(){
        var list = getLocalList(true);
        var localCheckObj = getLocalCheckOrDef();
        var localIndex = localCheckObj.index;
        var checkObj = list[localIndex];
        if(checkObj.dir == null || checkObj.dir == ''){
            list[0].checked = true;
            setLocalCheck(list[0])
        }else{
            list[localIndex].checked = true;
        }
        
        
        //渲染
        var localBookmark = document.getElementById('localBookmark').innerHTML;
        var elemView = document.getElementById('localBookmarkForm');
        // 渲染并输出结果
        var data = {list:list}
        laytpl(localBookmark).render(data, function(str){
            console.log(str)
            elemView.innerHTML = str;
            form.render(null,"localBookmarkForm")
        });


    }

    function renderSettingLocalDir(){
        var list = getLocalList();
        // 创建表格实例
        table.render({
            id:'local_table',
            elem: '#local_table',
            data: list, // 此处为静态模拟数据，实际使用时需换成真实接口
            page: false,
            toolbar: '<span>本地书签文件目录 <i id="tips_local" class="layui-icon layui-icon-tips layui-font-12" lay-on="tips_local"></i></span>',
            defaultToolbar: [],
            cols: [[
                {field:'index', width:60,title: '序号',unresize:true},
                {field:'alias', width:140,title: '别称', edit: 'text',unresize:true},
                {field:'dir', minWidth:500,title: '本地目录', edit: 'text',unresize:true},
            ]],
        });
    }


    var loadLocal = function(){
        dbObj = utools.db.get(db_id);

        var localDir = getLocalCheckOrDef().dir;

        window.services.readFile(localDir)
        .then( res => {
            try{
                var data = JSON.parse(res);
                tree.render({
                    elem: '#localTree',
                    data: data.roots.bookmark_bar.children,
                    showLine: false,
                    customName: { 
                        id: 'id',
                        title: 'name',
                        children: 'children'
                    }
                });
                layer.msg('加载完成',{offset:'16px',icon: 1})
            }catch(e){
                layer.msg('加载失败('+localDir+')<br>'+e.message,{offset:'16px',icon: 5})
            }
        })
        .catch(err => {
            if(err.errno == -4058){
                layer.msg('【本地书签地址】没找到：<br>'+err.path,{offset:'16px',icon: 5})
            }
        });
    }

    var loadRemote = function(){
        dbObj = utools.db.get(db_id);
        queryRemote(dbObj)
        .then(res => {
            try{
                var data = JSON.parse(Base64.decode(res.data.content));
                tree.render({
                    elem: '#remoteTree',
                    data: data.roots.bookmark_bar.children,
                    showLine: false,
                    customName: { 
                        id: 'id',
                        title: 'name',
                        children: 'children'
                    },
                });
                layer.msg('加载完成',{offset:'16px',icon: 1})
            }catch(e){
                layer.msg('加载失败 <br> 分支：'+dbObj.branch+'<br>文件：'+dbObj.remote_folder+'<br>'+e.message,{offset:'16px',icon: 5})
            }
        }).catch(giteeFailed);
    }


    var localPush = function(){
        var localFile;
        dbObj = utools.db.get(db_id);

        
        var localDir = getLocalCheckOrDef().dir;

        window.services.readFile(localDir)
        .then( res => {
            localFile = res;
            return queryRemote(dbObj);
        }).catch(err => {
            if(err.errno == -4058){
                layer.msg('【本地书签地址】没找到：<br>'+err.path,{offset:'16px',icon: 5})
            }
        })
        .then(data => {
            var sha = data.data.sha;
            pushRemote(dbObj,localFile,sha)
            .then(res => {
                console.log(res);
                layer.msg("推送成功",{offset:'16px',icon: 1})
            }).catch(giteeFailed);
            
        }).catch(giteeFailed)
    }

    $('#tips_token').on('click',function(){
        var elem = this;
        layer.tips('打开Gitee官网，登录，打开【个人设置】，找到【安全设置】下的【私人令牌】这一项，打开，接着生成私人令牌。私人令牌就是用户授权码(Token)。',
        elem,{closeBtn:2,time:0,tips: [2, '#16b777']})
    })
    $('#tips_user').on('click',function(){
        var elem = this;
        layer.tips('Gitee的个人空间地址。比如，我登录Gitee官网之后，我的浏览器地址是https://gitee.com/ji-song，那么仓库的拥有者就是ji-song',
        elem,{closeBtn:2,time:0,tips: [2, '#16b777']})
    })
    $('#tips_store').on('click',function(){
        var elem = this;
        layer.tips('自己建一个仓库用来存放你的书签文件，为了你的隐私安全，建议建一个私有的仓库。创建仓库的时候记得同时初始化仓库，只有初始化之后的仓库才能被本插件所使用。',
        elem,{closeBtn:2,time:0,tips: [2, '#16b777']})
    })
    $('#tips_remote').on('click',function(){
        var elem = this;
        layer.tips(' 你打算将书签存放到仓库的哪个路径下，例如我想将书签存放到仓库根目录下的Bookmarks文件中，那么这一项的值就可以填Bookmarks，如果我想将书签存放到仓库根目录下的bookmarks目录下的Bookmarks文件中，那么这一项的值就可以填bookmarks/Bookmarks',
        elem,{closeBtn:2,time:0,tips: [1, '#16b777']})
    })

    util.on({
        tips_local:function(){
            var elem = this;
            layer.tips('这个路径指的是你的Chrome浏览器书签文件的路径，查看该路径的办法：在Chrome浏览器中输入chrome://version/，然后在打开的页面中可以找到“Profile Path”，书签文件就是存放在“Profile Path”所指定的目录中（假设这个目录是/home/xxx/.config/google-chrome/Default）。Chrome浏览器的书签文件名为Bookmarks，那么书签存放路径这一项可以填：/home/xxx/.config/google-chrome/Default/Bookmarks',
            elem,{closeBtn:2,time:0,tips: [1, '#16b777']})
        }
    })

    form.on("radio",function(data){
        if(data.elem.name === 'localCheck'){
            var list = getLocalList(true);
            var index = data.value;
            var checked = list[index];
            if(null != checked && checked.dir != null && checked.dir != ''){
                dbObj = utools.db.get(db_id);
                setLocalCheck(checked)
            }
        }
    })
    
});

function setLocalCheck(checkObj){
    console.log('setLocalCheck',checkObj)
    localStorage.setItem('checkLocalDir',JSON.stringify(checkObj))
}

function getLocalCheckOrDef(){
    var str = localStorage.getItem('checkLocalDir');
    if(undefined== str || null == str || str == ''){
        var list = getLocalList(true)
        return list[0];
    }
    return JSON.parse(str);
}

function getLocalList(withDef){
    dbObj = utools.db.get(db_id);
    var list = [
        {index:1,alias:dbObj.local_folder_name||'--',dir:dbObj.local_folder||''},
        {index:2,alias:dbObj.local_folder1_name||'--',dir:dbObj.local_folder1||''},
        {index:3,alias:dbObj.local_folder2_name||'--',dir:dbObj.local_folder2||''},
    ]
    if(withDef){
        var path = window.services.getBookmarksPath()
        list.unshift({index:0,alias:'*自动识别',dir:path})
    }
    return list;
}

function saveToDb(data){
    console.log('save',data)
    var dbObj = utools.db.get(db_id);
    data._id = db_id;
    if(null != dbObj && null != dbObj._rev){
        data._rev = dbObj._rev
    }
    if(null == data.branch || '' == data.branch ){
        data.branch = "master";
    }
    utools.db.put(data)
}

function giteeFailed(err){
    console.log(err)
    if(err.response.status == 404){
        layer.msg("码云 404，确认以下是否都存在：<br>【用户名】【仓库】【远程目录地址】",{offset:'16px',icon: 5})
    }
    if(err.response.status == 401){
        layer.msg("码云 401，确认以下是否都正确：<br>【Token】",{offset:'16px',icon: 5})
    }
}


function queryRemote(dbObj){
    return new Promise((resolve, reject) => {  
        var url = 'https://gitee.com/api/v5/repos/'+dbObj.username+'/'+dbObj.storehouse+'/contents/'+dbObj.remote_folder
        var param = {
            access_token : dbObj.token ,
            ref : dbObj.branch || 'master'
        }
        axios.get(url,{
            params:param
        })
        .then(resolve)
        .catch(reject)
    })
}

function pushRemote(dbObj,content,sha){
    var base64Content = Base64.encode(content)
    return new Promise((resolve, reject) => {  
        var url = 'https://gitee.com/api/v5/repos/'+dbObj.username+'/'+dbObj.storehouse+'/contents/'+dbObj.remote_folder
        var param = {
            access_token : dbObj.token ,
            branch : dbObj.branch || 'master',
            message: 'utools-bookmark-push',
            content: base64Content,
            sha: sha
        }
        axios.put(url,param)
        .then(resolve)
        .catch(reject)
    })
}